package com.vvlive.caibao.smartcity.base;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by zhj on 2015/9/10.
 * 简化ListView，GridView的Adapter操作
 * @param <T>
 */
public abstract class SuperAdapter<T> extends BaseAdapter {

//    class Test extends SuperAdapter<String>{
//
//        public Test(Context context, int itemId, List<String> dataList) {
//            super(context, itemId, dataList);
//        }
//
//        @Override
//        public void onBindData(ViewHolder viewHolder, String s, int position) {
//
//        }
//    }

    private int mItemId;
    private List<T> mDataList;
    private LayoutInflater mInflater;

    public abstract void onBindData(ViewHolder viewHolder, T t, int position);

    public SuperAdapter(Context context, int itemId, List<T> dataList) {
        mInflater = LayoutInflater.from(context);
        mItemId = itemId;
        mDataList = dataList;
    }

    @Override
    public int getCount() {
        return mDataList.size();
    }

    @Override
    public Object getItem(int position) {
        return mDataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView == null) {
            convertView = mInflater.inflate(mItemId, null);
        }

        onBindData(ViewHolder.createHolder(convertView), (T) getItem(position), position);

        return convertView;
    }

    //
    public static final class ViewHolder {

        private static final ViewHolder VIEWHOLDER = new ViewHolder();
        public static View itemView;

        public static ViewHolder createHolder(View itemView){
            ViewHolder.itemView = itemView;
            return VIEWHOLDER;
        }

        public <T extends View> T get(int id) {

            SparseArray<View> viewHolder = (SparseArray<View>) itemView.getTag();
            if (viewHolder == null) {
                viewHolder = new SparseArray<View>();
                itemView.setTag(viewHolder);
            }
            View childView = viewHolder.get(id);
            if (childView == null) {
                childView = itemView.findViewById(id);
                viewHolder.put(id, childView);
            }
            return (T) childView;
        }

    }

}
